package com.tanhua.admin.listener;

import com.alibaba.fastjson.JSON;
import com.tanhua.admin.mapper.LogMapper;
import com.tanhua.model.admin.Log;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class LogListener {

    @Autowired
    private LogMapper logMapper;

    /**
     * 监听日志信息，并向数据库写入日志
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(
                    value = "tanhua.log.queue",//创建消息队列
                    durable = "true"
            ),
            exchange = @Exchange(
                    value = "tanhua.log.exchange",//确认交换机
                    type = ExchangeTypes.TOPIC//模式为主题模式
            ),
            key = {
                    "log.*"//接收主题
            }
    ))
    public void listenCreate(String message) {

        try {
            Map<String, Object> map = JSON.parseObject(message);
            //获取数据
            Long userId = (Long) map.get("userId");
            String date = (String) map.get("date");
            String objId = (String) map.get("objId");
            String type = (String) map.get("type");
            Log log = new Log(userId, date, type);

            logMapper.insert(log);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
